<?php
/*
 * 信息发布使用, 图片上传
 * @package    sys
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: d684693b51d17a88a9ff33fa9eba2432caa47700 $
 */
defined('IN_IXDCW') or exit('Access Denied');

/**
 * 发布以及发布检测类
 * Class Post
 */
class Post {

	/**
	 * 需要加载seajs, 文件上传组件
	 * @param        $id
	 * @param        $moduleid
	 * @param        $source
	 * @param        $postName
	 * @param string $old
	 * @return string
	 */
	public static function thumbUpload($id, $moduleid, $source, $postName, $old = '') {
		global $_userid, $_username, $_groupid;
		$prevId = 'prev_' . preg_replace('/[\[\]]/', '_', $postName);
		Session::start();
		$data = "
		<input type=\"text\" name=\"" . $postName . "\" size=\"60\" id=\"" . $prevId . "\" readonly=\"readonly\" value=\"{$old}\"><span onclick=\"_preview($('" . $prevId . "').val());\" class=\"jt\">[预览]</span>
		<script>
		seajs.use(['uploadify', 'upload', 'uploadify-css'], function (uploadify, upload) {
			$(function () {
				$('#" . $id . "').uploadify({
					'formData' : {
						'uMid' : '" . $moduleid . "',
						'uSource' : '" . $source . "',
						'uUid': '" . $_userid . "',
						'uUsername': '" . $_username . "',
						'uGroupid': '" . $_groupid . "',
						'uPHPSESSID':'" . session_id() . "',
						'uAuth': '" . Auth::genSwfUpload($_userid, $_username, $_groupid) . "',
						'uOld': '" . $old . "'
					},
					'swf' : ixdcw.domain.cssjs+'js/libs/uploadify/3.2.0/uploadify.swf',
					'uploader' : ixdcw.domain.cssjs+'upload/thumb.php',
					'multi':false,
					'fileTypeExts':'*.jpg;*.jpeg;*.png;*.gif',
					'fileTypeDesc':'图片类型',
					'fileSizeLimit':'500k',
					'buttonText':'浏览...',
					'width':50,
					'height':22,
					'onUploadSuccess':upload.uploadThumbSucess
				});
			});
		});
		</script>";
		return $data;
	}

	/**
	 * 图片上传框
	 * @param        $moduleid
	 * @param        $source
	 * @param        $postName
	 * @param string $old
	 * @param        $ext
	 * @return string
	 */
	public static function thumb($moduleid, $source, $postName, $old = '', $ext) {
		global $_userid;
		$MOD  = PCache::read('module-' . $moduleid . '.php');
		$w    = $MOD[$source . '_width'];
		$h    = $MOD[$source . '_height'];
		$auth = md5($_SERVER['HTTP_USER_AGENT'] . Env::ip() . $_userid);
		$id   = preg_replace('/[\[\]]/', '_', $postName);
		$data = "
		<input type=\"hidden\" name=\"uploadSeName\" value=\"" . $moduleid . '_' . $source . "\">
		<input type=\"text\" name=\"" . $postName . "\" size=\"40\" class=\"easyui-input\" id=\"" . $id . "\" readonly=\"readonly\" value=\"{$old}\" data-old=\"{$old}\" {$ext}>
		<a id=\"upload_{$id}\" class=\"easyui-linkbutton\">上传</a>
		<a id=\"preview_{$id}\"  class=\"easyui-linkbutton\">预览</a>
		<script>
		seajs.use(['mod-upload'], function(upload){
			$('#upload_" . $id . "').on('click',function() {
				upload.open('{$id}', '{$moduleid}', '{$source}', '{$auth}', '{$old}')
			});
			$('#preview_{$id}').on('click', function(){
				upload.preview($('#{$id}').val(), {$w}, {$h});
			});
		});
		</script>
		";
		return $data;
	}

	/**
	 * 图片上传框
	 * @param        $moduleid  上传的文件夹
	 * @param        $source    缩略图没别的意思
	 * @param        $postName
	 * @param string $old       原图片，上传过的图片的位置
	 * @param        $width
	 * @param        $height
	 * @param        $ext
	 * @return string
	 */
	public static function picture($moduleid, $source, $postName, $old = '', $width = 320, $height = 240, $ext = '') {
		global $_userid, $_username, $_groupid;
		$sessionGroup = $moduleid . '_' . $source;
		PictureUpload::clearSession($sessionGroup, true);
		$auth = Auth::genSwfUpload($_userid, $_username, $_groupid);
		$id   = self::postNameToId($postName);
		$data = <<<Picture
		<input type="text" name="{$postName}" size="40" class="easyui-input" id="{$id}" readonly="readonly" value="{$old}" data-old="{$old}" {$ext}>
		<a id="upload_{$id}" class="easyui-linkbutton" iconCls="icon-add">上传</a>
		<a id="preview_{$id}"  class="easyui-linkbutton" iconCls="icon-search">预览</a>
		<a id="clear_{$id}"  class="easyui-linkbutton" iconCls="icon-cancel">清空</a>
		<script>
		seajs.use(['mod-upload','$', 'easyui-css', 'easyui', 'easyui-icon-css'], function(upload, $){
		$(function(){
			$('#upload_{$id}').on('click',function() { upload.open('{$id}', '{$moduleid}', '{$source}', '{$auth}', '{$old}', {$width}, {$height}) });
			$('#preview_{$id}').on('click', function(){ upload.preview($('#{$id}').val(), {$width}, {$height}); });
			$('#clear_{$id}').on('click', function(){ $('#{$id}').val(''); });
		});
		});
		</script>
Picture;
		return $data;
	}

	public static function postNameToId($postName) {
		return preg_replace('/[\[\]]/', '_', $postName);
	}

	/**
	 * 单车系选择, 是否使用快捷输入方式
	 * @param     $brandPost
	 * @param     $carPost
	 * @param int $brandDefault
	 * @param int $carDefault
	 * @param int $brandInput
	 * @param int $carInput
	 * @return string
	 */
	public static function autocomboCar($brandPost, $carPost, $brandDefault = 0, $carDefault = 0, $brandInput = 0, $carInput = 0) {
		$brandPostId = self::postNameToId($brandPost);
		$carPostId   = self::postNameToId($carPost);
		if (!isset($brandDefault) || empty($brandDefault)) $brandDefault = 0;
		if (!isset($carDefault) || empty($carDefault)) $carDefault = 0;
		if ($brandInput) $brandInput = 'true';
		if ($carInput) $carInput = 'true';

		$itemWidth = 180;
		$doc       = <<< SCRIPT
<select class="easyui-combobox" id="$brandPostId" name="$brandPost"></select>
<select class="easyui-combobox" id="$carPostId" name="$carPost"></select>
<script>
	seajs.use(['mod-url', 'easyui', 'easyui-css'], function (url) {
		var brandDefault = $brandDefault;
		var carDefault = $carDefault;
		var brandUrl = url.auto + '?action=autoBrands';
		var carUrl = url.auto + '?action=autoCars';

		if ( brandDefault ) {
			brandUrl += '&aDft=' + brandDefault;
			carUrl += '&aBid=' + brandDefault;
		}

		if ( carDefault ) {
			if ( !brandDefault ) {
				$.messager.alert('品牌没有默认值, 请检查输入');
				return;
			}
			carUrl += '&aDft=' + carDefault;
		}

		var carOption = {disabled : true};
		if ( carDefault || brandDefault ) {
			carOption = {
				disabled : false,
				url : carUrl,
				valueField : 'carId',
				textField : 'carName',
				width : $itemWidth,
				required : true,
				editable : $carInput
			};
		}

		var \$brand = $('#$brandPostId').combobox({
			required : true,
			multiple : false,
			width : $itemWidth,
			editable : $brandInput,
			url : brandUrl,
			valueField : 'brandId',
			textField : 'brandName',
			mode : 'local',
			filter: function(ipt, row) {
				var opts = $(this).combobox('options');
				return row[opts.textField].indexOf(ipt.toUpperCase()) >= 0;
			},
			onSelect : function (ele) {
				// get new Info
				\$car.combobox({
					disabled : false,
					url : carUrl + '&aBid=' + ele.brandId,
					width : $itemWidth,
					valueField : 'carId',
					textField : 'carName',
					required : true,
					editable : $carInput
				}).combobox('clear');
			}
		});
		var \$car = $('#$carPostId').combobox(carOption);
	})
</script>
SCRIPT;
		return $doc;
	}

	/**
	 * 车款选择的easyui方式
	 * @param        $brandPost    品牌表单
	 * @param        $carPost      车系表单
	 * @param        $modelPost    车款表单
	 * @param string $brandDefault 品牌默认, 以 ',' 分隔的字串
	 * @param string $carDefault   车系默认
	 * @param string $modelDefault 车款默认
	 * @param bool   $brandMulti   品牌多选
	 * @param bool   $carMulti     车系是否多选
	 * @param bool   $modelMulti   车款是否多选
	 * @param bool   $allRequired  车款是否多选
	 * @return string
	 */
	public static function autocombo(
		$brandPost, $carPost, $modelPost,
		$brandDefault = '', $carDefault = '', $modelDefault = '',
		$brandMulti = true, $carMulti = true, $modelMulti = true,
		$allRequired = false
	) {
		// todo
		$brandPostId  = self::postNameToId($brandPost);
		$carPostId    = self::postNameToId($carPost);
		$modelPostId  = self::postNameToId($modelPost);
		$brandMulti   = $brandMulti ? 'true' : 'false';
		$carMulti     = $carMulti ? 'true' : 'false';
		$modelMulti   = $modelMulti ? 'true' : 'false';
		$brandDefault = $brandDefault ? $brandDefault : '';
		$carDefault   = $carDefault ? $carDefault : '';
		$modelDefault = $modelDefault ? $modelDefault : '';
		if ($allRequired) {
			$brandRequired = 'true';
			$carRequired   = 'true';
			$modelRequired = 'true';
		} else {
			$brandRequired = 'false';
			$carRequired   = 'false';
			$modelRequired = 'false';
		}

		$itemWidth = 180;
		$doc       = <<< SCRIPT
<select class="easyui-combobox" id="$brandPostId" name="$brandPost" ></select>
<select class="easyui-combobox" id="$carPostId" name="$carPost"></select>
<select class="easyui-combobox" id="$modelPostId" name="$modelPost"></select>
<script>
	seajs.use(['mod-url', 'easyui', 'easyui-css'], function (url) {
		var brandDefault = [$brandDefault];
		var carDefault = [$carDefault];
		var modelDefault = [$modelDefault];
		var brandUrl = url.auto + '?action=autoBrands';
		var carUrl = url.auto + '?action=autoCars';
		var modelUrl = url.auto + '?action=autoModels';
		if (brandDefault.length) {
			carUrl += '&aBid='+brandDefault.join(',');
		}
		if (carDefault.length) {
			modelUrl += '&aCid='+carDefault.join(',');
		}
		// init
		var brandOption = {
			required : $brandRequired,
			multiple : $brandMulti,
			width : $itemWidth,
			url : brandUrl,
			valueField : 'brandId',
			textField : 'brandName',
			editable:false,
			mode : 'local',
			missingMessage:'请选择品牌',
			onSelect : function (ele) {
				var brandId = \$brand.combobox('getValues');
				if (brandId) {
					// get new Info
					var cOption = \$car.combobox('options');
					cOption.url =  carUrl + '&aBid=' + \$brand.combobox('getValues');
					cOption.disabled = false;
					carDefault = [];
					\$car.combobox(cOption).combobox('clear');
				}
			}
		};
		var carOption = {
			required: $carRequired,
			missingMessage:'请选择车系',
			disabled : true,
			multiple : $carMulti,
			valueField : 'carId',
			textField : 'carName',
			editable:false,
			width : $itemWidth,
			onSelect : function (ele) {
				// get new Info
				var cOption = \$model.combobox('options');
				cOption.url =  modelUrl + '&aCid='+ \$car.combobox('getValues');
				cOption.disabled = false;
				modelDefault = [];
				\$model.combobox(cOption).combobox('clear');
			}
		};
		var modelOption={
			required: $modelRequired,
			missingMessage:'请选择车款',
			disabled : true,
			multiple : $modelMulti,
			editable:false,
			valueField : 'modelId',
			textField : 'modelName',
			width : $itemWidth
		};

		var \$brand = $('#$brandPostId').combobox(brandOption);
		var \$car = $('#$carPostId').combobox(carOption);
		var \$model = $('#$modelPostId').combobox(modelOption);
		if (brandDefault.length) {
			var bOption = \$brand.combobox('options');
			bOption.url=brandUrl;
			bOption.onLoadSuccess = function() {
				\$brand.combobox('setValues', brandDefault);
			};

		}
		\$brand.combobox(bOption);
		if (carDefault.length) {
			var cOption = \$car.combobox('options');
			cOption.disabled = false;
			cOption.url=carUrl;
			cOption.onLoadSuccess = function() {
				\$car.combobox('setValues', carDefault);
			};
			\$car.combobox(cOption);
		}

		if (modelDefault.length) {
			var mOption = \$model.combobox('options');
			mOption.url=modelUrl;
			mOption.disabled = false;
			mOption.onLoadSuccess = function() {
				\$model.combobox('setValues', modelDefault);
			};
			\$model.combobox(mOption);
		}
	})
</script>
SCRIPT;
		return $doc;
	}

	/**
	 * 地区选择, 附带权限地区刷新
	 * @param        $postname
	 * @param        $default
	 * @param string $extend
	 * @param bool   $isAjax
	 * @param string $mid
	 * @param string $authCity
	 * @param bool   $isDisabled
	 * @return string
	 */
	public static function areaCombo($postname, $default = 0, $extend = '', $isAjax = false, $mid = '', $authCity = '', $isDisabled = false) {
		global $AREA, $moduleid;
		$moduleid   = !empty($mid) ? $mid : ($moduleid ? $moduleid : 0);
		$auth       = Area::auth($moduleid);
		$id         = self::postNameToId($postname);
		$AREA       = !empty($AREA) ? $AREA : PCache::read('area.php');
		$isDisabled = $isDisabled ? 'true' : 'false';
		if ($default) {
			$strPids = $AREA[$default]['arrparentid'];
		} else {
			$strPids = '0';
		}

		$arrPids = explode(',', $strPids);
		if ($AREA[$default]['child']) {
			$arrPids[] = $default;
		}

		$areas = array();
		foreach ($arrPids as $pid) {
			$areas[$pid] = (array) __($AREA)->filter(function ($item) use ($pid) {
				return $item['parentid'] == $pid;
			});
		}

		$keys   = array_keys($areas);
		$values = array();
		foreach ($keys as $k => $v) {
			if (isset($keys[$k + 1])) {
				$values[$v] = $keys[$k + 1];
			} else {
				if (!$AREA[$default]['child']) {
					$values[$v] = $default;
				} else {
					$values[$v] = '';
				}
			}
		}

		if ($auth > 0 && $auth < 4 && count($areas) > 2) {
			for ($i = 0; $i < 4 - $auth; $i++) {
				array_shift($areas);
				array_shift($values);
			}
		}

		$formatArea = __($areas)->map(function ($item, $index) use ($values) {
			return array(
				'areas'   => json_encode(__($item)->map(function ($sItem) {
					return array(
						'areaId'   => $sItem['areaid'],
						'areaName' => $sItem['areaname'],
					);
				})),
				'key'     => $index,
				'default' => $values[$index],
			);
		});

		$tpl = <<<areaCombo
		{{^isAjax}}
		<input type="hidden" name="{{postname}}" id="{{id}}" value="{{default}}" {{extend}}>
		<span id="container_{{id}}">
		{{/isAjax}}
		{{# formatArea }}
        <input id="area_{{id}}{{key}}" value="{{# default }}{{default}}{{/ default }}">
		{{/ formatArea }}
		<script>
		seajs.use(['lm-util', 'easyui', 'easyui-css'], function (util) {
		$(function(){
		{{# formatArea }}
			$('#area_{{id}}{{key}}').combobox({
			    data:{{{areas}}},
			    valueField:'areaId',
			    textField:'areaName',
			    disabled:{{isDisabled}},
			    onSelect: function(area){
			        {{# formatArea }}
		            $('#area_{{id}}{{key}}').combobox('destroy');
		            {{/ formatArea }}
			        util.areaCombo('{{id}}', {action:'areaCombo',aPid:area.areaId, aPostName:'{{postname}}', aMid:{{moduleid}}}, '{{&ajaxUrl}}');
		        }
			});
		{{/ formatArea }}
		})
		});
		</script>
		{{^isAjax}}
		</span>
		{{/isAjax}}
areaCombo;
		$m   = new Mustache_Engine;
		return $m->render($tpl, array(
				'postname'   => $postname,
				'id'         => $id,
				'default'    => $default,
				'extend'     => $extend,
				'formatArea' => $formatArea,
				'isAjax'     => $isAjax,
				'moduleid'   => $moduleid,
				'current'    => $AREA[$authCity]['areaname'],
				'isDisabled' => $isDisabled,
				'ajaxUrl'    => ajaxUrl('common/areaCombo'),
			)
		);
	}

	/**
	 * 类别级联选择, 仅仅选择一项
	 * @param        $postname
	 * @param        $default
	 * @param        $mid
	 * @param string $extend
	 * @param bool   $isAjax
	 * @param int    $disabledLevel
	 * @return string
	 */
	public static function cateCombo($postname, $default, $mid, $extend = '', $isAjax = false, $disabledLevel = 0) {

		$default  = !empty($default) ? $default : 0;
		$moduleid = intval($mid);
		$id       = self::postNameToId($postname);
		$CATEGORY = !empty($CATEGORY) ? $CATEGORY : PCache::read('category-' . $mid . '.php');

		if (!$default || !isset($CATEGORY[$default])) {
			$first   = __($CATEGORY)->first();
			$default = $first['catid'];
		}

		$strPids = $CATEGORY[$default]['arrparentid'];
		$arrPids = explode(',', $strPids);
		if ($CATEGORY[$default]['child']) {
			$arrPids[] = $default;
		}
		$cates = array();
		foreach ($arrPids as $pid) {
			$cates[$pid] = (array) __($CATEGORY)->filter(function ($item) use ($pid) {
				return $item['parentid'] == $pid;
			});
		}

		$keys   = array_keys($cates);
		$values = array();
		foreach ($keys as $k => $v) {
			if (isset($keys[$k + 1])) {
				$values[$v] = $keys[$k + 1];
			} else {
				if (!$CATEGORY[$default]['child']) {
					$values[$v] = $default;
				} else {
					$values[$v] = '';
				}
			}
		}

		$oldDisabledLevel = $disabledLevel;
		$formatCate       = __($cates)->map(function ($item, $index) use ($values, &$disabledLevel) {
			$disabledLevel--;
			return array(
				'cates'    => json_encode(__($item)->map(function ($sItem) {
					return array(
						'cateId'   => $sItem['catid'],
						'cateName' => $sItem['catname'],
					);
				})),
				'disabled' => ($disabledLevel >= 0) ? 'true' : 'false',
				'key'      => $index,
				'default'  => $values[$index],
			);

		});
		$tpl              = <<<cateCombo
		{{^isAjax}}
		<input type="hidden" name="{{postname}}" id="{{id}}" value="{{default}}" {{extend}}>
		<span id="container_{{id}}">
		{{/isAjax}}
		{{# formatCate }}
        <input class="js_cate_change" id="cate_{{id}}{{key}}" value="{{default}}">
		{{/ formatCate }}
		<script>
		seajs.use(['$', 'lm-util', 'easyui', 'easyui-css'], function ($, utils) {
		$(function(){
		{{# formatCate }}
			$('#cate_{{id}}{{key}}').combobox({
			    data:{{{cates}}},
			    valueField:'cateId',
			    textField:'cateName',
			    disabled:{{disabled}},
			    onSelect: function(cate){
			        {{# formatCate }}
		            $('#cate_{{id}}{{key}}').combobox('destroy');
		            {{/ formatCate }}
			        utils.cateCombo('{{id}}', {action:'cateCombo',aPid:cate.cateId, aPostName:'{{postname}}', aMid:{{moduleid}}, aDisabled:{{disabledLevel}}}, '{{&ajaxUrl}}');
		        }
			});
		{{/ formatCate }}
		})
		});
		</script>
		{{^isAjax}}
		</span>
		{{/isAjax}}
cateCombo;
		$m                = new Mustache_Engine;

		return $m->render($tpl, array(
				'postname'      => $postname,
				'id'            => $id,
				'default'       => $default,
				'extend'        => $extend,
				'formatCate'    => $formatCate,
				'isAjax'        => $isAjax,
				'moduleid'      => $moduleid,
				'disabledLevel' => $oldDisabledLevel,
				'ajaxUrl'       => ajaxUrl('common/cateCombo'),
			)
		);
	}

	/**
	 * KindEditor 编辑器
	 * @param $name
	 * @param $modelid
	 * @param $default
	 * @param $extend
	 * @param $width
	 * @param $height
	 * @return string
	 */
	public static function kindEditor($name, $modelid, $default, $extend, $width = '100%', $height = '400px') {
		global $_userid, $_username, $_groupid;
		$source = 'editor';
		PictureUpload::clearSession($modelid . '_' . $source, true);
		$id      = self::postNameToId($name);
		$auth    = Auth::genSwfUpload($_userid, $_username, $_groupid);
		$default = htmlspecialchars($default);
		$data    = <<<KindEditor
		<textarea name="$name" id="$id" $extend>$default</textarea>
		<script>
		seajs.use([ 'ke', 'mod-url'], function ( ke, url) {
			lemon.editor = lemon.editor || {};
			lemon.editor.{$id} = ke.create('#{$id}',{
				extraFileUploadParams:{
					'uMid' : '$modelid',
					'uSource' : '$source',
					'uUid': '$_userid',
					'uAuth': '$auth'
				},
                uploadJson : url.editorUpload,
                items:ke.iConfig.dft,
                width: '$width',
                height:'$height',
                resizeType: 1,
                allowFlashUpload:false
			});
			lemon.editor.{$id}.sync();
		});
		</script>
KindEditor;
		return $data;
	}

	/**
	 * 选择
	 * @param        $items
	 * @param        $name
	 * @param array  $default
	 * @param string $selectedValue
	 * @param string $extend
	 * @param bool   $useKey
	 * @return string
	 */
	public static function select($items, $name, $selectedValue = '-', $default = array('-' => '请选择'), $extend = '', $useKey = true) {
		$selectText = "<select name=\"{$name}\"";
		$selectText .= $extend ? " {$extend}>" : '>';
		$selectText .= PHP_EOL;

		$selectedValue = strval($selectedValue);
		if ($default) {
			$items = array_merge($default, $items);
		}

		foreach ($items as $k => $v) {
			$k        = strval($k);
			$selected = ($useKey ? $k : $v) == $selectedValue ? ' selected="selected"' : '';
			$selectText .= "\t<option value=\"" . ($useKey ? $k : $v) . '"' . $selected . ">{$v}</option>" . PHP_EOL;
		}
		$selectText .= '</select>' . PHP_EOL;
		return $selectText;
	}

	/**
	 * 日期选择
	 * @param        $name
	 * @param string $default
	 * @param string $option
	 * @param bool   $quickSelect
	 * @return string
	 */
	public static function calender($name, $default = '', $option = '', $quickSelect = false) {
		global $DT_TIME;
		$option = '{' . $option . '}';
		$id     = self::postNameToId($name);
		$idSelect = 'select_'.$id;
		$data   = "<input id=\"{$id}\" name=\"{$name}\" value=\"{$default}\">";
		if ($quickSelect) {
			$times = array(
				'3'=>'三天',
				'7'=>'一周',
				'15'=>'半月',
				'30'=>'一月',
				'182'=>'半年',
				'365'=>'一年',
			);
			$data .= "
				&nbsp;
				<select id=\"$idSelect\">
					<option value=\"\">长期</option>";

			foreach($times as $day => $desc){
				$data .= "<option value=\"".timetodate($DT_TIME+86400*$day, 3)."\">{$desc}</option>";
			}
			$data .= "</select>";
		}
		$data .='<script>
		seajs.use(["$", "easyui", "easyui-css"], function ($) {
			$(function(){
				$("#'.$id.'").datebox('.$option.');'."\n";
		if ($quickSelect) {
			$data .= "$('#$idSelect').change(function(){
				\$('#$id').datebox('setValue', $('#$idSelect').val());
			});";
		}
		$data .= "});})</script>";
		return $data;
	}

	/**
	 * 时间日期选择
	 * @param        $name
	 * @param string $default
	 * @param string $option
	 * @return string
	 */
	public static function datetimeBox($name, $default = '', $option = '') {
		$option = '{' . $option . '}';
		$id     = self::postNameToId($name);
		$data   = "
		<input id=\"{$id}\" name=\"{$name}\" value=\"{$default}\">
		<script>
		seajs.use(['$', 'easyui', 'easyui-css'], function ($) {
			$(function(){
				$('#{$id}').datetimebox({$option});
			})
		});
		</script>";
		return $data;
	}

	/**
	 * 类目选择
	 * @param $name
	 * @param $moduleid
	 * @param $title
	 * @param $default
	 * @param $extend
	 * @return string
	 */
	public static function catTree($name, $moduleid, $title, $default, $extend = '') {
		$filename = 'catetree-' . $moduleid;
		return self::_selectTree($name, $filename, $title, $default, $extend);
	}

	/**
	 * 汽车类目选择
	 * @param $name
	 * @param $rank
	 * @param $title
	 * @param $default
	 * @param $extend
	 * @return string
	 */
	public static function autocatTree($name, $rank, $title, $default, $extend = '') {
		$filename = 'autoCategoryTree-' . $rank;
		return self::_selectTree($name, $filename, $title, $default, $extend);
	}


	/**
	 * 检测是否是用户名
	 * @param $file
	 * @return int
	 */
	public static function useridByFile($file) {
		$file = basename($file);
		if (preg_match("/^([0-9a-zA-Z]{1}+)_(.+)\./", $file, $m)) {
		} else {
			return 0;
		}
	}

	/**
	 * 清除A链接
	 * @param $content
	 * @return mixed
	 */
	public static function clearLink($content) {
		$content = preg_replace("/<a[^>]*>/i", "", $content);
		return preg_replace("/<\/a>/i", "", $content);
	}

	/**
	 * @param        $content
	 * @param string $ext
	 * @param int    $self
	 * @return mixed 将远程的图片保存到本地
	 */
	public static function saveRemote($content, $ext = 'jpg|jpeg|gif|png|bmp|swf', $self = 0) {
		global $DT, $moduleid, $_userid, $CFG;
		if (!$_userid || !$content) return $content;
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;
		$urls = $oldpath = $newpath = array();
		foreach ($matches[2] as $k => $url) {
			if (in_array($url, $urls)) continue;
			$urls[$url] = $url;
			if (strpos($url, '://') === false) continue;
			if (strpos($url, '.' . $CFG['domain'] . '/') !== false) continue;

			$file_ext = File::ext($url);
			$relative = Picture::name($moduleid, $_userid, $file_ext);

			if ($CFG['ftpImg']) {
				// save to ftp temp
				$aim      = DT_CACHE . '/ftp/' . basename($relative);
				$ftpLocal = $aim;
			} else {
				// save to local and check file
				$aim = DT_ROOT . '/' . $relative;
			}
			if (File::copyto($url, $aim)) {
				if (is_image($aim)) {
					if (!@getimagesize($aim)) {
						File::del($aim);
						continue;
					}
					if ($DT['water_type']) {
						$image = new image($aim);
						if ($DT['water_type'] == 2) {
							$image->waterimage();
						} else if ($DT['water_type'] == 1) {
							$image->watertext();
						}
					}
				}
				if ($CFG['ftpImg']) {
					// then save to ftp
					$ftpAim = $relative;
					$ftp    = new Ftp($CFG['ftpImg']);
					if (!$ftp->isDir(dirname($ftpAim))) {
						$ftp->mkDirRecursive(dirname($ftpAim));
					}
					$ftp->put($ftpAim, $ftpLocal, FTP_BINARY);
					File::del($ftpLocal);
				}
				$oldpath[] = $url;
				$newpath[] = Picture::url($relative);
			}
		}
		unset($matches);
		return str_replace($oldpath, $newpath, $content);
	}


	/**
	 * 保存缩略图
	 * @param     $content
	 * @param     $no
	 * @param int $width
	 * @param int $height
	 * @return string
	 */
	public static function saveThumb($content, $no, $width = 120, $height = 90) {
		global $DT, $CFG, $_userid, $moduleid;
		if (!$_userid || !$content) return '';
		$ext = 'jpg|jpeg|gif|png|bmp';
		if (!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return '';
		foreach ($matches[2] as $k => $url) {
			if ($k == $no - 1) {
				$file_ext   = File::ext($url);
				$originName = Picture::name($moduleid, $_userid, $file_ext);
				$thumbName  = Picture::name($moduleid, $_userid, $file_ext);

				$ftpTmp   = DT_CACHE . '/ftp/' . basename($originName);
				$ftpThumb = DT_CACHE . '/ftp/' . basename($thumbName);

				$fileAim = Picture::realpath($thumbName);

				if (File::copyto($url, $ftpTmp)) {
					if (is_image($ftpTmp)) {
						if (!@getimagesize($ftpTmp)) {
							File::del($ftpTmp);
							continue;
						}
						if ($DT['water_type']) {
							$image = new image($ftpTmp);
							if ($DT['water_type'] == 2) {
								$image->waterimage();
							} else if ($DT['water_type'] == 1) {
								$image->watertext();
							}
						}
					}
					$image = new image($ftpTmp);
					$image->thumb($width, $height, 1, $ftpThumb);
					File::del($ftpTmp);
					if ($CFG['ftpImg']) {
						// then save to ftp
						$ftpAim = Picture::relative($fileAim);
						$ftp    = new Ftp($CFG['ftpImg']);
						if (!$ftp->isDir(dirname($ftpAim))) {
							$ftp->mkDirRecursive(dirname($ftpAim));
						}
						$ftp->put($ftpAim, $ftpThumb, FTP_BINARY);
						File::del($ftpThumb);
					} else {
						File::copyto($ftpThumb, $fileAim);
						File::del($ftpThumb);
					}
				}
				return Picture::url($thumbName);
			}
		}
		unset($matches);
		return '';
	}

	/**
	 * 检测发布内容的长度
	 * @param $title
	 * @param $length
	 * @return bool
	 */
	public static function checkLength($title, $length) {
		$stripTitle = Filter::vtitle($title);
		if (Str::length($stripTitle) >= $length) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * tree 选择方式
	 * @param $name
	 * @param $filename
	 * @param $title
	 * @param $default
	 * @param $extend
	 * @return string
	 */
	private static function _selectTree($name, $filename, $title, $default, $extend) {
		$id       = self::postNameToId($name);
		$treeFile = DT_CACHE . "/{$filename}.php";
		PCache::sysCategory();
		if (file_exists($treeFile)) {
			$tree        = "<option value=\"\">{$title}</option>";
			$treeContent = file_get_contents($treeFile);
			if ($default) {
				$preg        = "/(<option\s+value=\"{$default}\")/";
				$treeContent = preg_replace($preg, '$1 selected="selected"', $treeContent);
			}
			$tree .= $treeContent;
		} else {
			$tree = '<option value="0">尚未更新缓存,请更新缓存文件</option>';
		}
		$data = <<<SELECT
			<select id="{$id}" name="{$name}" {$extend}>
				{$tree}
			</select>
SELECT;
		return $data;
	}

	/**
	 * @param     $content 有待截取的内容
	 * @param int $length  带截取的长度
	 * @return mixed|string 截取内容的一部分
	 */
	public static function intro($content, $length = 0) {
		if ($length) {
			$intro = trim(Str::trimEOL(strip_tags($content)));
			// 删除实体
			$intro = preg_replace("/&([a-z]{1,});/", '', $intro);
			return Str::cut($intro, $length);
		} else {
			return '';
		}
	}

	public static function htmlEmbed($code, $width = 550, $height = 400) {
		$data = <<<EMBED
<embed src="http://player.youku.com/player.php/sid/{$code}/v.swf" type="application/x-shockwave-flash" width="{$width}" height="{$height}" quality="high" />
EMBED;
		return $data;
	}

	/**
	 * 基于PHPCMS的多图上传提取, 使用seajs 封装
	 * @param       $post
	 * @param       $modulelid
	 * @param array $oldImages
	 * @return string
	 */
	public static function multiUpload($post, $modulelid, $oldImages = array()) {
		global $_userid, $_username, $_groupid;
		$id        = self::postNameToId($post);
		$args      = array(
			'uUid'  => $_userid,
			'uAuth' => Auth::genSwfUpload($_userid, $_username, $_groupid),
			'uMid'  => $modulelid
		);
		$url       = apiUrl('upload/multi', $args);
		$strImages = '';
		foreach ($oldImages as $img) {
			$strImages .= '<p class="multi-imgs" id="image_' . $img['itemid'] . '">
			<img src="' . $img['thumb'] . '" height="80" title="双击查看原图"><br>
			<input type="hidden" name="' . $id . '_url[]" value="' . $img['thumb'] . '" style="width:310px;" class="input-text">
			<input type="text" name="' . $id . '_alt[]" value="' . $img['intro'] . '" style="width:160px;" class="input-text" onfocus="if(this.value == this.defaultValue) this.value = \'\'"onblur="if(this.value.replace(\' \',
					\'\') == \'\') this.value = this.defaultValue;"> <br><a data-removeid="image_' . $img['itemid'] . '" href="javascript:void(0)">移除</a> </p>';
		}

		$content = "
<link rel=\"stylesheet\" href=\"" . CSS_URL . "multiUpload/multi.css\" />
<script>
		seajs.use(['$','multiUtil', 'artDialog-css'],function($,multiUtil){
			// 多图上传
			var change_images = multiUtil.change_images;

			$('#J_Upload_{$id}').click(function(){
				multiUtil.flashupload('{$url}', 'images_{$id}', '多图上传','{$post}',change_images);
			});
			$('#{$id}').on('click','a[data-removeId]',function(){
				var imgId = $(this).attr('data-removeId');
				multiUtil.remove_div(imgId);
			});
			$('#{$id}').on('dblclick','img',function(){
				var imgUrl = $(this).attr('src');
				multiUtil.image_preview(imgUrl);
			})
    });
</script>
<div style=\"margin: 0 auto;\">
    <input name=\"{$post}\" type=\"hidden\" value=\"1\">
    <fieldset class=\"blue pad-10\">
        <legend>图片列表</legend>
        <div id=\"{$id}\" class=\"picList\">
			{$strImages}
        </div>
    </fieldset>
    <div class=\"bk10\"></div>
    <div class=\"picBut cu\">
        <a id=\"J_Upload_{$id}\" href=\"javascript:void(0);\"> 选择图片 </a>
    </div>
</div>";
		return $content;
	}

	/**
	 * 检测是否是图片
	 * @param $file
	 * @return int
	 */
	public static function isImage($file) {
		return preg_match("/^(jpg|jpeg|gif|png|bmp)$/i", File::ext($file));
	}
}